<?php
class JournalController extends Zend_Controller_Action {
	function init() {
		$this->view->action = $this->getRequest()->getControllerName();
		$route = new Zend_Controller_Router_Route(
        	":module/:id",
		array(
				"controller" => "journal",
				"action" => "index"
				),
				array("id" => "\d+")
				);
		$this->journal = new Zend_Db_Table('journal');
		$this->comment = new Zend_Db_table('comment');
		$this->users = new Zend_Db_table('users');
	}
	public function indexAction() {
		$url = $this->getRequest()->getParam('url')? $this->getRequest()->getParam('url') : '';
		if($url != '') {
			$journal = $this->journal->fetchRow(
				$this->journal
					->select()
					->where("`url` =  '$url'")
			);
			$author = $this->comment->fetchRow(
				$this->users
					->select()
					->where("id = $journal->author_id")
			);
			$comments = $this->comment->fetchAll(
				$this->comment
					->select()
					->where("journal_id = $journal->id")
					->order('published ASC')
			);
			$this->view->journal = (object) $journal->toArray();
			$this->view->journal->comments = (object) $comments->toArray();
			$this->view->journal->comments_count = $comments->count();
			$this->view->journal->author = (object) $author->toArray();
		} else {
			$all_journals = $this->journal->fetchAll(
				$this->journal
					->select()
					->where('author_id = 1')
					->order('published ASC')
					->limit(10, 0)
			);
			if($all_journals->count() > 0) {
				$this->view->journals = array();
				foreach($all_journals as $b) {
					$journal = (object) array();
					$author = $this->comment->fetchRow(
						$this->users
							->select()
							->where("id = $b->author_id")
					);
					$comments = $this->comment->fetchAll(
						$this->comment
							->select()
							->where("journal_id = $b->id")
							->order('published ASC')
					);
					$journal->id = $b->id;
					$journal->title = $b->title;
					$journal->url = $b->url;
					$journal->published = $b->published;
					$journal->content = $b->content;
					$journal->author->id = $author->id;
					$journal->author->name = $author->name;
					$journal->author->website = $author->website;
					$journal->comments_count = $comments->count();
					$this->view->journals[] = $journal;
				}
			}
		}
	}
}